package com.pine.app.module.security.oauth.config;

import com.pine.app.module.security.core.matcher.AntPathRequestMatcher;
import com.pine.app.module.security.core.matcher.OrRequestMatcher;
import com.pine.app.module.security.core.matcher.RequestMatcher;
import com.pine.app.module.security.oauth.provider.AuthenticationManager;
import com.pine.app.module.security.oauth.provider.sso.RouteOauthAuthenticationManager;
import com.pine.app.module.security.oauth.filter.OAuth2ClientAuthenticationProcessingFilter;
import com.pine.app.module.security.oauth.config.properties.OAuth2SsoProperties;
import com.pine.app.module.security.oauth.provider.sso.token.AuthorizationCodeSsoTokenHandler;
import com.pine.app.module.security.oauth.provider.sso.token.OAuth2SsoTokenHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

/**
 * @author xiaoyuan
 * @create 2020/3/19 11:31
 **/
@Configuration
@Conditional(EnableOAuth2SSOCondition.class)
@Slf4j
@Order(100)
public  class OAuth2SSODefaultConfiguration extends WebSecurityConfiguration{


    private OAuth2SsoProperties clientOauth2Properties;

    public OAuth2SSODefaultConfiguration(OAuth2SsoProperties oAuth2ClientProperties){
        this.clientOauth2Properties = oAuth2ClientProperties;
    }

    @Bean
    public AuthenticationManager getRouteOauthAuthenticationManager() {
        RouteOauthAuthenticationManager authenticationManager = new RouteOauthAuthenticationManager();
        authenticationManager.setClientId(clientOauth2Properties.getClient_id());
        authenticationManager.setClientSecret(clientOauth2Properties.getClient_secret());
        authenticationManager.setCheckTokenEndpointUrl(clientOauth2Properties.getAccess_token_validate_uri());
        return authenticationManager;
    }

    @Bean
    public OAuth2ClientAuthenticationProcessingFilter oAuth2ClientAuthenticationProcessingFilter() {
        //哪些请求被过滤处理
        RequestMatcher requestMatcher = new OrRequestMatcher(
                new AntPathRequestMatcher(clientOauth2Properties.getLoginPath(), "GET")
        );
        OAuth2ClientAuthenticationProcessingFilter oAuth2ClientAuthenticationProcessingFilter=  new OAuth2ClientAuthenticationProcessingFilter();
        oAuth2ClientAuthenticationProcessingFilter.setRequestMatcher(requestMatcher);
        return oAuth2ClientAuthenticationProcessingFilter;
    }


    @Bean
    public OAuth2SsoTokenHandler oAuth2SsoTokenHandler() {
        return new AuthorizationCodeSsoTokenHandler(clientOauth2Properties);
    }

}
